package com.muye.dianli.activity;

import java.nio.charset.Charset;
import java.util.ArrayList;

import org.apache.http.entity.mime.content.StringBody;

import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.muye.constant.C;
import com.muye.constant.ConstantPersonalInfo;
import com.muye.constant.U;
import com.muye.dianli.BaseActivity;
import com.muye.dianli.MainActivity;
import com.muye.dianli.R;
import com.muye.field.LoginField;
import com.muye.field.LoginFieldData;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.data.utils.DataSP;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 登录页面
 * 
 * @author TangChao
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener, OnKeyListener, TextWatcher, OnCheckedChangeListener
{
	/**
	 * 用户名输入框
	 */
	private EditText userEdit;
	
	/**
	 * 用户名
	 */
	private String userStr;
	
	/**
	 * 密码输入框
	 */
	private EditText passwordEdit;
	
	/**
	 * 密码
	 */
	private String passwordStr;
	
	/**
	 * 请求数据线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	/**
	 * 登录返回字段
	 */
	private LoginFieldData loginFieldData;
	
	/**
	 * 记住密码
	 */
	private CheckBox rememberPasswordBtn;
	
	/**
	 * 账户信息存储数据库
	 */
	DataSP dataSP = new DataSP(this, C.ACCOUNT_INFO);
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.login_layout);
		createTitle();
		initWidget();
		userStr = dataSP.getSValue(C.USER_NAME, "");
		passwordStr = dataSP.getSValue(C.PASSWORD, "");
		if (passwordStr != null && !passwordStr.equals(""))
		{
			passwordEdit.setText(passwordStr);
			rememberPasswordBtn.setChecked(true);
		}
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
	
	/**
	 * 初始化控件
	 */
	private void initWidget()
	{
		// 账号输入框
		userEdit = (EditText) findViewById(R.id.user_input_edit);
		userEdit.setText(dataSP.getSValue(C.USER_NAME, ""));
		userEdit.addTextChangedListener(this);
		// 密码输入框
		passwordEdit = (EditText) findViewById(R.id.password_input_edit);
		passwordEdit.addTextChangedListener(this);
		// 记住密码勾选框
		rememberPasswordBtn = (CheckBox) findViewById(R.id.password_input_remember);
		rememberPasswordBtn.setEnabled(false);
		rememberPasswordBtn.setOnCheckedChangeListener(this);
		// 登录按钮
		TextView loginBtn = (TextView) findViewById(R.id.sliding_menu_layout_user_image);
		loginBtn.setOnClickListener(this);
		// 注册新账户按钮
		TextView registNewBtn = (TextView) findViewById(R.id.new_register_btn);
		registNewBtn.setOnClickListener(this);
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle()
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText("点利商盟");
		titleName.setTextColor(getResources().getColor(R.color.white));
		ImageView leftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		leftBtn.setImageResource(R.drawable.title_back_icon);
		leftBtn.setVisibility(View.VISIBLE);
		leftBtn.setOnClickListener(this);
	}
	
	/**
	 * 请求登录
	 */
	private void login()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		try
		{
			String str = C.APPID + passwordStr + userStr + C.CONSTANT;
			paramsList.add(new KeyValue<String, Object>("appId", new StringBody(C.APPID, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("pass", new StringBody(passwordStr, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("phone", new StringBody(userStr, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
			requestHttpPostThread = new RequestHttpPostThread(loginListener, U.LOGIN, paramsList);
			requestHttpPostThread.start();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 请求登录返回监听
	 */
	private RequestHttpListener loginListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				try
				{
					byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
					String str = new String(dataArr, "utf-8");
					Log.i(C.TAG, "登陆结果" + str);
					Gson gson = new Gson();
					LoginField loginField = gson.fromJson(str, LoginField.class);
					loginFieldData = loginField.data;
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 0;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:
					if (msg.arg1 == HttpConst.ACTION_SUCCESS)
					{
						try
						{
							ConstantPersonalInfo.account = userEdit.getText().toString();
							ConstantPersonalInfo.uid = loginFieldData.id;
							ConstantPersonalInfo.name = loginFieldData.name;
							ConstantPersonalInfo.lastTime = loginFieldData.last;
							ConstantPersonalInfo.mobilePhone = loginFieldData.phone;
							ConstantPersonalInfo.sex = loginFieldData.sex;
							ConstantPersonalInfo.address = loginFieldData.address;
							ConstantPersonalInfo.birth = loginFieldData.birth;
							ConstantPersonalInfo.longitude = loginFieldData.longitude;
							ConstantPersonalInfo.latitude = loginFieldData.latitude;
							ConstantPersonalInfo.email = loginFieldData.email;
							ConstantPersonalInfo.status = loginFieldData.status;
							ConstantPersonalInfo.integral = loginFieldData.integral;
							ConstantPersonalInfo.token = loginFieldData.token;
							Intent intent = new Intent(LoginActivity.this, MainActivity.class);
							startActivity(intent);
							finish();
						}
						catch (Exception e)
						{
							e.printStackTrace();
						}
					}
					else if (msg.arg1 == HttpConst.ACTION_FAIL)
					{
						C.showToast(getApplicationContext(), R.string.fail_request_data);
					}
					break;
				
				default:
					break;
			}
		}
		
	};
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_left_image_view:
				finish();
				break;
			case R.id.sliding_menu_layout_user_image:// 登录按钮
				if (userStr == null || userStr.equals(""))
				{
					C.showToast(this, "请输入你的账号");
					return;
				}
				if (passwordStr == null || passwordStr.equals(""))
				{
					C.showToast(this, "请输入你的密码");
					return;
				}
				login();
				break;
			case R.id.new_register_btn:// 注册新账户按钮
				Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivity(intent);
				break;
			
			default:
				break;
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		if (requestHttpPostThread != null)
		{
			requestHttpPostThread.interrupt();
			requestHttpPostThread.setRequestHttpListener(null);
		}
		return false;
	}
	
	@Override
	public void afterTextChanged(Editable s)
	{
		rememberPasswordBtn.setEnabled(false);
		userStr = userEdit.getText().toString();
		passwordStr = passwordEdit.getText().toString();
		if (passwordStr != null && !passwordStr.equals(""))
		{
			rememberPasswordBtn.setEnabled(true);
		}
		dataSP.setValue(C.USER_NAME, userEdit.getText().toString());
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after)
	{
		
	}
	
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count)
	{
		
	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
	{
		switch (buttonView.getId())
		{
			case R.id.password_input_remember:// 密码
				if (isChecked)
				{
					dataSP.setValue(C.USER_NAME, userEdit.getText().toString());
					dataSP.setValue(C.PASSWORD, passwordEdit.getText().toString());
				}
				else
				{
					dataSP.setValue(C.PASSWORD, "");
					passwordEdit.setText("");
					rememberPasswordBtn.setChecked(false);
				}
				break;
			
			default:
				break;
		}
	}
	
}
